/*
 * Copyright (c) 2014-2017 Texas Instruments Incorporated - http://www.ti.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 *  ======== custom.c ========
 */

#include <assert.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdbool.h>
#include <stdio.h>

/* TI-RTOS Header files */
#include <ti/display/Display.h>
#include <ti/drivers/GPIO.h>
#include <ti/drivers/I2C.h>
#include <ti/drivers/dpl/ClockP.h>
#include <ti/drivers/net/wifi/simplelink.h>
#include <ti/drivers/storage/nvs.h>

/* Example/Board Header files */
#include "Board.h"
#include "custom.h"

#include <ti/hap/ip/HAPEngine.h>
#include <ti/mfi/mfiauth.h>
#include <ti/rng/rng.h>

#include "netwifi.h"
#include "accessory.h"
#include "doodad.h"

#define POLLFXNTIMEOUT 5000 /* milliseconds */
#define DEBOUNCETIME 200 /* milliseconds */
#define HAPSTOPTIMEOUT 1000 /* milliseconds */
#define SLSTOPTIMEOUT 200
#define NUMIDBYTES 6
#define HAPDEVICEIDLEN 17 + 1 /* +1 for null term char */
#define APP_DATA "custom_app_data"

typedef struct App_Data {
    unsigned char deviceID[NUMIDBYTES];
} App_Data;

int waitForButton(void);
void appInit(bool reset);

HAPEngine_Handle engineHandle;
sem_t btnSem, stopSem;
char apName[] = "custom";
uint32_t prevTicks = 0xFFFF;
uint32_t curTicks, msPeriod;
App_Data appData;
char deviceIDBuf[HAPDEVICEIDLEN];
static Display_Handle display;
static MFiAuth_Handle mfih = { .handle = NULL };

void gpioButtonFxn0(uint_least8_t index)
{
    curTicks = ClockP_getSystemTicks();
    msPeriod = ClockP_getSystemTickPeriod() / 1000;

    if ((curTicks - prevTicks) >= (DEBOUNCETIME/msPeriod)) {
        if (engineHandle) {
            sem_post(&btnSem);
        }
    }
    prevTicks = curTicks;
    GPIO_clearInt(Board_BUTTON0);
}

/* Fxn to poll for button press to run WAC at network bootup*/
int waitForButton(void)
{
    static int curButton, prevButton;

    GPIO_toggle(Board_LED0);
    curButton = GPIO_read(Board_BUTTON0);
    if ((curButton == 0) && (prevButton != 0)) {
        return NETWIFI_RUNWAC;
    }
    prevButton = curButton;
    return NETWIFI_PROCEED;
}

void *buttonHandlerFxn(void *arg)
{
    int status;

    while (1) {
        sem_wait(&btnSem);
        status = HAPEngine_stop(engineHandle, HAPSTOPTIMEOUT);
        if (status == HAPEngine_EOK) {
            sem_post(&stopSem);
        }
    }
}

void appInit(bool reset)
{
    unsigned int size = sizeof(appData);
    int status;

    if (reset || NVS_get(APP_DATA, &appData, 0, &size) != NVS_EOK) {
        RNG_setRandomSeed(NULL);
        RNG_getRandomBytes(appData.deviceID, NUMIDBYTES);
        status = NVS_set(APP_DATA, &appData, 0, sizeof(App_Data), 0);
        assert(status == NVS_EOK);
    }
}

/*
 *  ======== serverFxn ========
 *  Initializes WiFi module and runs HAPEngine server
 */
void *serverFxn(void *arg)
{
    int status;
    int mfiStatus;
    HAPEngine_AccessoryDesc *accs[1];
    unsigned long IPAddress;
    HAPEngine_Params params;

    /* open controller for the MFi chip */
    mfih.handle = I2C_open(Board_I2C_MFI, NULL);
    assert(mfih.handle != NULL);
    mfiStatus = MFiAuth_setDevice(&mfih, Board_MFI_ADDR);

    /* open the display for output */
    display = Display_open(Display_Type_UART, NULL);
    assert(display != NULL);

    Display_printf(display, 0, 0, "HomeKit custom example");

    sl_Start(NULL,NULL,NULL);

    /* Init HAPEngine */
    HAPEngine_init();

    /* Has to be called after HAPEngine_init since NVS needs to initialized */
    appInit(false);

    sl_Stop(SLSTOPTIMEOUT);

    /*
     * Note, if mfiStatus is equal to MFiAuth_EAUTHCHIPNOTFOUND there is no MFi
     * chip detected, therefore if WAC_run is called inside here it will fail
     */
    status = NetWiFi_waitForNetwork(apName, appData.deviceID, waitForButton,
                                        POLLFXNTIMEOUT, &IPAddress);

    assert(status == NETWIFI_SUCCESS);

    Display_printf(display, 0, 0,
            "CC3220 has connected to AP and acquired an IP address.");
    Display_printf(display, 0, 0, "IP Address: %d.%d.%d.%d",
            SL_IPV4_BYTE(IPAddress,3), SL_IPV4_BYTE(IPAddress,2),
            SL_IPV4_BYTE(IPAddress,1), SL_IPV4_BYTE(IPAddress,0));

    /* Enable interrupt for reset button */
    GPIO_enableInt(Board_BUTTON0);

    /* Initialize accessory descriptor with run-time supplied info */
    status = accessory_init(&accessory_services);
    assert(status == HAPEngine_EOK);
    HAPEngine_Params_init(&params);

    /* Conditionally add MFi-based pairing (if the chip is detected) */
    Display_printf(display, 0, 0, "MFiAuth: %d", mfiStatus);
    if (mfiStatus == 0) {
        params.mfiRespAndCertFxn = &MFiAuth_getRespAndCert;
    }

    accs[0] = &accessory_services;

    do {

        snprintf(deviceIDBuf, HAPDEVICEIDLEN,
                "%02x:%02x:%02x:%02x:%02x:%02x",
                appData.deviceID[0], appData.deviceID[1],
                appData.deviceID[2], appData.deviceID[3],
                appData.deviceID[4], appData.deviceID[5]);

        /* Create HAP Engine */
        engineHandle = HAPEngine_create(accs, 1, deviceIDBuf,
                    HAPEngine_CI_OTHER, &custom_getSetupCodeFxn, &params);
        assert(engineHandle != NULL);

        /*
         * Run HAP server. This internally loops handling client requests
         * and may never return.
         */
        status = HAPEngine_serve(engineHandle, NULL, 0);
        assert(status == HAPEngine_EOK);

        /* pend until HAPEngine_stop returns */
        sem_wait(&stopSem);

        /* delete the HAPEngine */
        status = HAPEngine_delete(&engineHandle);
        assert(status == HAPEngine_EOK);

        HAPEngine_reset();
        appInit(true);
        Display_printf(display, 0, 0, "HomeKit Factory Reset");

    } while(1);
}
